import React, { useEffect, useRef, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Space, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { exportExcel } from '@/utils/ExportExcel';
import { getSort, setLsetData } from '@/utils/utils';
import CDel from '@/components/common/CDel';
import { getAdminList } from '@/services/admin/common/api';
import { getList, del, delAll } from '@/services/admin/log/operationLog/api';
import CDelAll from '@/components/common/CDelAll';
import Details from './components/Details';
const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [adminList, setAdminList] = useState<any>({});
  const fetchApi = async () => {
    const adminRes = await getAdminList();
    if (adminRes.status == 20000) {
      const adminData = [];
      for (let i = 0; i < adminRes.data.length; i++) {
        adminData[adminRes.data[i].id] = {
          text: adminRes.data[i].username,
          status: adminRes.data[i].id,
        };
      }
      if (adminData.length) await setAdminList({ ...adminData });
    }
  };
  useEffect(() => {
    fetchApi();
  }, []);
  let maps = {};
  const columns: ProColumns<API.AdminOperationLogList>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      hideInSearch: true,
      align: 'center',
      width: 80,
      fixed: true,
    },
    {
      title: '操作名称',
      dataIndex: 'name',
      align: 'center',
      width: 80,
      render: (text, record) => <Details {...record} />,
    },
    {
      title: '管理员',
      dataIndex: 'admin_one',
      hideInSearch: true,
      width: 70,
      align: 'center',
      render: (text, record) => [<span key={record.id}>{record.admin_one?.username}</span>],
    },
    {
      title: '管理员',
      dataIndex: 'admin_id',
      valueType: 'select',
      valueEnum: adminList,
      hideInTable: true,
    },
    {
      title: '操作接口',
      dataIndex: 'url',
      align: 'center',
      width: 100,
    },
    {
      title: '操作路由',
      dataIndex: 'pathname',
      align: 'center',
      width: 100,
    },
    {
      title: '请求方式',
      dataIndex: 'method',
      align: 'center',
      width: 80,
      valueType: 'select',
      valueEnum: {
        GET: { text: 'GET', status: 'Default' },
        POST: {
          text: 'POST',
          status: 'Error',
        },
        PUT: {
          text: 'PUT',
          status: 'Success',
        },
        DELETE: {
          text: 'DELETE',
          status: 'Processing',
        },
      },
    },
    {
      title: '请求IP',
      dataIndex: 'ip',
      align: 'center',
      width: 80,
    },
    {
      title: '操作时间',
      dataIndex: 'created_at',
      key: 'created_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 160,
      align: 'center',
    },
    {
      title: '操作时间',
      key: 'created_at',
      dataIndex: 'created_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            'created_at[0]': value[0],
            'created_at[1]': value[1],
          };
        },
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 80,
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (_, row) => [
        <CDel
          key={row.id}
          onCancel={async () => {
            const res = await del(row.id);
            if (res.status === 20000) {
              message.success(res.message);
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },
  ];
  return (
    <PageContainer fixedHeader={true} title={false}>
      <ProTable
        scroll={{ x: 1000 }}
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (params: API.ListQequest, sort) => {
          const data = await getSort(params, sort);
          const res = await getList(data);
          return setLsetData(res);
        }}
        options={{ fullScreen: true }}
        rowSelection={{ fixed: true }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        columnsState={{
          onChange: (map) => {
            maps = map;
          },
        }}
        tableAlertOptionRender={({ selectedRows, selectedRowKeys, onCleanSelected }) => {
          return (
            <Space size={16}>
              <CDelAll
                key={selectedRowKeys.length}
                count={selectedRowKeys.length}
                onCancel={async () => {
                  const res = await delAll({ idArr: selectedRowKeys });
                  if (res.status === 20000) {
                    message.success(res.message);
                    actionRef.current?.reload();
                    onCleanSelected();
                  }
                }}
              />
              <a
                onClick={async () => {
                  const selectedRowsCope = JSON.parse(JSON.stringify(selectedRows));
                  selectedRowsCope.map((item: any) => {
                    item.admin_one = item.admin_one?.username || '';
                  });
                  exportExcel({
                    fileName: '操作日志',
                    columns,
                    maps,
                    selectedRows: selectedRowsCope,
                  });
                }}
              >
                导出数据
              </a>
            </Space>
          );
        }}
      />
    </PageContainer>
  );
};
export default Index;
